package com.ashafa.server;

public class UTF8Encoder {

	
	public static byte[] encode(String s) {
	    final char[] chars = s.toCharArray();
	    int elen;

	    // Compute encoded length
	    elen = 0;
	    for (int i = 0; i < s.length(); i++) {
	        int ch = chars[i];
	        if (ch >= 0x0001 && ch <= 0x007f)
	                elen++;
	        else if (ch == 0x0000 || (ch >= 0x0080 && ch <= 0x07ff))
	                elen += 2;
	        else
	                elen += 3;
	    }

	    // Do the actual encoding
	    byte[] data = new byte[elen];
	    elen = 0;
	    for (int i = 0; i < s.length(); i++) {
	        int ch = chars[i];
	        if (ch >= 0x0001 && ch <= 0x007f)
	                data[elen++] = (byte)ch;
	        else if (ch == 0x0000 || (ch >= 0x0080 && ch <=
	0x07ff)) {
	            data[elen++] = (byte)(0xc0 | ((ch >> 6) & 0x1f));
	            data[elen++] = (byte)(0x80 | (ch & 0x3f));
	        } else {
	            data[elen++] = (byte)(0xe0 | ((ch >> 12) & 0x0f));
	            data[elen++] = (byte)(0x80 | ((ch >> 6) & 0x3f));
	            data[elen++] = (byte)(0x80 | (ch & 0x3f));
	        }
	    }
	    return data;
	}

}
